/**
 */
;
(function(){
'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.controller('WarningResultAuditCtrl', ['$scope','$modal','$state','CaseCommonService', '$http','$upload','$location',
	                                  '$stateParams','WarningAddService','BaseURL','Modal','WarningScreenService','FwaTabsetService',
	    function ($scope,$modal,$state,CaseCommonService,$http,$upload,$location,
	    		                       $stateParams,WarningAddService,baseUrl,Modal,WarningScreenService,FwaTabsetService) {
		$scope.serv = WarningAddService;
		var warnNo=$stateParams.warnNo,
			staffCode=[],
			insurCode=[],
		    screen=[];
		$scope.saveDialogload=true;
		$scope.warningFrom={};
		$scope.warningFrom.date={};
		$scope.notice = {};
		$scope.resultNotice = {};
		$scope.warnInsurCount=0;
		$scope.warnStaffCount=0;
		$scope.warnMedicalCount=0;
		$scope.warnInsurData=[];
		$scope.warnStaffData=[];
		$scope.warnMedicalData={};
		$scope.warnScreenList=[];
		$scope.prcoessTypeFlag=false;
		$scope.tabs=[];
		
		/****tab页面*/
		function setTabInfo(){
			$scope.tabs=[{name:'网上筛查',status:0,index:0,url:'views/hcpms/warning/warnView/warningViewScreen_view.html'},
			             {name:'自查结果',status:0,index:1,url:'views/hcpms/warning/warnView/warningSelfExamResult_view.html'},
			             {name:'结果评估',status:0,index:2,url:'views/hcpms/warning/warnView/warningResultQuery_view.html'},
			             {name:'复审意见',status:1,index:3,url:'views/hcpms/warning/warnEdit/warningEditResultAudit_view.html'}];
			$scope.currentTab = 3;
			$scope.currentTabIndex = 3;
			$scope.tabClick = function(index) {
				$scope.currentTab = index;
				$scope.currentTabIndex=index;
			}
		}
		setTabInfo();
		function queryWarning(){
			WarningAddService.getHcpmsWarning({warnNo:warnNo})
			.success(function(res){
					$scope.warningFrom=res.warnInfo;
					if(res.warnStaffList){
						$scope.warnStaffData=res.warnStaffList;
						$scope.warnStaffCount=res.warnStaffList.length;
						angular.forEach($scope.warnStaffData,function(data,index){
							 if($.inArray(data.code, staffCode) === -1){
								 staffCode.push(data.code);
							 }
						 });
			         }
					if(res.warnInsuranceList){
						$scope.warnInsurData=res.warnInsuranceList;
						$scope.warnInsurCount=res.warnInsuranceList.length;
						angular.forEach($scope.warnInsurData,function(data,index){
							if($.inArray(data.code, insurCode) === -1){
								insurCode.push(data.code);
							 }
						 });
			          }
					if(res.warnScreenList){
						$scope.warnScreenList=res.warnScreenList;
						angular.forEach($scope.warnScreenList,function(data,index){
							screen.push(data.monitorNo+data.ruleNo);
						 });
					 }
					if(res.notice){
						$scope.notice=res.notice;
					}
	        		if(res.warnMedicalInfo){
	        			$scope.warnMedicalData=res.warnMedicalInfo;
	        			$scope.warnMedicalCount=1;
	        		}
	        		if($scope.warningFrom.process==='02'||$scope.warningFrom.process==='04'){	
        				$scope.prcoessTypeFlag=true;
        				getNoticeDate();
        			}
	        		if($scope.warningFrom&&$scope.warningFrom.isCheckBack=='1'){
	        			var pageFive= {name:'审批意见',status:1,index:4,url:baseUrl+'views/hcpms/warning/warnView/warningQueryExamine_view.html'};		        		
	        			$scope.tabs.push(pageFive);
					}
	        		WarningScreenService.findPointCutTempScose(
	      				   WarningAddService.warningMarks,$stateParams.warnNo,'01',
	      				   $scope.warnMedicalData,$scope.warnStaffData,$scope.warnInsurData);
		     });
		}
		queryWarning();
		//获取结果告知书
		function getNoticeDate(){
			WarningAddService.getWarnNotice({warnNo:warnNo})
			.success(function(res){
				if(res.resultNotice){
					$scope.resultNotice=res.resultNotice;
				}
			});
		}
		//查看案件来源
		$scope.viewDetailWarning = function(){
			var scope = $scope.$new();
			scope.warningFrom = $scope.warningFrom;
			var modalInstance = $modal.open({
	      	      templateUrl: baseUrl +'views/hcpms/warning/warnView/warningViewBase_view.html',
	      	      backdrop:'static',
				  size:'sm',
				  scope:scope,
	      	      controller:function($modalInstance,$scope){
					  $scope.onOk = function(){
				  		   $modalInstance.dismiss();
				  	   }	
				  }
	  	    });	
		}
		//自查通知书
		$scope.warningNoticeDialog = function() {
			var scope = $scope.$new();
			scope.warningNotice=$scope.notice;
			scope.warningNotice.date=WarningAddService.setPriodDate(scope.warningNotice.datestart,scope.warningNotice.dateend);
			var modalInstance = $modal.open({
	      	      templateUrl: baseUrl +'views/hcpms/warning/warnView/warningViewNotice_view.html',
	      	      backdrop:'static',
				  size:'sm',
				  scope:scope,
	      	      controller:function($modalInstance,$scope){
	      	    	 $scope.$watch('$viewContentLoaded',function(){
	      	    		 downFile('03','warningViewNoticeOpenpdf');
	      	    	  });
					  $scope.onOk = function(){
				  		   $modalInstance.dismiss();
				  	   }	
				  }
	  	    });
		}
		
		/**打开PDF文件*/
		   function downFile(param,openpdfId){
		   			var success = new PDFObject({ url:baseUrl+'HcpmsWarnDownFile/downPdfFile.do?warnNo='+warnNo+'&docType='+param+'&warnNoBiz='+$scope.warningFrom.warnNoBiz,
		   				pdfOpenParams: { navpanes: 1,
		                 toolbar: 1,
		                 statusbar: 1,
		                 view: 'FitV',
		                 pagemode: 'thumbs'
		   			}}).embed(openpdfId);
		   }
		
	/*	function downFile(param){
			window.location = baseUrl+'HcpmsWarnDownFile/downPdfFile.do?warnNo='+warnNo+'&docType='+param+'&warnNoBiz='+$scope.warningFrom.warnNoBiz;
		}*/
		function getNoticeDate(){
			WarningAddService.getWarnNotice({warnNo:warnNo})
			.success(function(res){
				if(res.resultNotice){
					$scope.resultNotice=res.resultNotice;
				}
			});
		}
		//结果告知书
		$scope.warnResultToldDialog = function (){
			var scope = $scope.$new();
			scope.warnNotice=$scope.resultNotice;
			var modalInstance = $modal.open({
	      	      templateUrl: baseUrl +'views/hcpms/warning/warnEdit/warningEditResultNoticeDialog_view.html',
	      	      backdrop:'static',
				  size:'sm',
				  scope:scope,
	      	      controller:'WarningAddResultNoticeCtrl'
	  	    });
			 modalInstance.result.then(function(item) {
				 $scope.resultNotice=item;
			 });
		}
		//新增参保人员
		$scope.addInsurance = function() {
			var modalInstance = $modal.open({
			      templateUrl: baseUrl+'views/hcpms/warning/warnEdit/warningAddInsurDialog_view.html',
			      backdrop:'static',
				  size:'sm',
				  controller: 'WarningAddInsurCtrl'
			    });
			 modalInstance.result.then(function(item) {
				 angular.forEach(item,function(data,index){
					 if($.inArray(data.code, insurCode) === -1){
						 $scope.warnInsurData.push(data);
						 insurCode.push(data.code);
					 }
				 });
				 $scope.warnInsurCount=$scope.warnInsurData.length;
	 	    });
		}
		//删除参保人员
		$scope.deleteInsurance = function (data){
			Modal.confirm('确认删除参保人'+data.name+'吗？',function(){
				WarningScreenService.deleteMark(WarningAddService.warningMarks,3,data);//mark:1.机构，2.医务人员，3.参保人
				$scope.warnInsurData.splice($.inArray(data,$scope.warnInsurData),1);			
				insurCode.splice($.inArray(data.code,insurCode),1);
				$scope.warnInsurCount=$scope.warnInsurData.length;
			});
		}
		//新增医护人员
		$scope.addStaff = function() {
			var modalInstance = $modal.open({
			      templateUrl: baseUrl+'views/hcpms/warning/warnEdit/warningAddStaffDialog_view.html',
			      backdrop:'static',
				  size:'sm',
				  controller: 'WarningAddStaffCtrl'
			    });
			 //接收返回数据
			 modalInstance.result.then(function(item) {
				 angular.forEach(item,function(data,index){
					 if($.inArray(data.code, staffCode) === -1){
						 $scope.warnStaffData.push(data);
						 staffCode.push(data.code);
					 }
				 });
				 $scope.warnStaffCount=$scope.warnStaffData.length;
	 	    });
		}
		//删除医护人员
		$scope.deleteStaff = function (data){
			Modal.confirm('确认删除医护人员'+data.name+'吗？',function(){
				WarningScreenService.deleteMark(WarningAddService.warningMarks,2,data);//mark:1.机构，2.医务人员，3.参保人
				$scope.warnStaffData.splice($.inArray(data,$scope.warnStaffData),1);
				staffCode.splice($.inArray(data.code,staffCode),1);
				$scope.warnStaffCount=$scope.warnStaffData.length;
			});
		}
		//查看参保人员详细信息
		$scope.viewInsurList = function(){
			var scope = $scope.$new();
			scope.warnInsuranceList=$scope.warnInsurData;
			var modalInstance = $modal.open({
			      templateUrl: baseUrl+'views/hcpms/warning/warnView/warningViewInsurance_view.html',
			      backdrop:'static',
				  size:'sm',
				  scope:scope,
				  controller:function($modalInstance,$scope){
					  $scope.onOk = function(){
				  		   $modalInstance.dismiss();
				  	   }	
				  }
			    });
			
		}
		//查看医护人员详细信息
		$scope.viewStaffList = function(){
			var scope = $scope.$new();
			scope.warnStaffList=$scope.warnStaffData;
			var modalInstance = $modal.open({
				  templateUrl: baseUrl+'views/hcpms/warning/warnView/warningViewStaff_view.html',
			      backdrop:'static',
				  size:'sm',
				  scope:scope,
				  controller:function($scope,$modalInstance){
		  	          //取消或或者直接关闭
					  $scope.onOk = function(){
						  $modalInstance.dismiss();
			          }	
				  }
			    });
			
		}
		//查看医疗机构详细信息
		$scope.viewMedicalInfo = function(){
            if(!$scope.warnMedicalData){
            	return;
            }
			var scope = $scope.$new();
			$scope.medical=$scope.warnMedicalData;
			var modalInstance = $modal.open({
				  templateUrl: baseUrl+'views/hcpms/warning/warnView/warningViewMedical_view.html',
			      backdrop:'static',
				  size:'sm',
				  scope:scope,
				  controller:function($scope,$modalInstance){
		  	          //取消或或者直接关闭
					  $scope.onOk = function(){
						  $modalInstance.dismiss();
			          }	
				  }
			    });
			
		}
		//隐藏扣分以及删除按钮
		$scope.mouseoutShow = function(data){
			data.show = false;
		}
		
        //显示扣分以及删除按钮
		$scope.mouseoverShow = function(data){
			data.show = true;
		}
		
		//自查结果
		$scope.selfResult = {};
		$scope.selfResultList =[];
		function getSelfExamResult(){
			WarningAddService.getWarnCheckResult({warnNo:warnNo}).
			success(function(res){
				if(res.checkResults){
					$scope.selfResult = res.checkResults;
					$scope.selfResult.checkSumamount=parseFloat(res.checkResults.checkSumamount).toFixed(2);
				}
				if(res.detailList){
					$scope.selfResultList = res.detailList;
				}
			});
		}
		getSelfExamResult();
		/**自查结果评估**/
		$scope.assessResult={};
		$scope.assessResultList=[];
		function getAssessResult(){
			WarningAddService.getWarnResult({warnNo:warnNo}).
			success(function(res){
				if(res.warnResult){
					$scope.assessResult = res.warnResult;
					$scope.assessResult.sumAmount=parseFloat(res.warnResult.sumAmount).toFixed(2);
				}
				if(res.warnResultList){
					$scope.assessResultList = res.warnResultList;
				}
				if(!$scope.auditResult.sumAmount){
					$scope.auditResult.sumAmount=$scope.assessResult.sumAmount;
				}
				if(!$scope.resultNotice.amount&&$scope.auditResult.sumAmount){
					$scope.resultNotice.amount=$scope.auditResult.sumAmount;
				}
			});
		}
		getAssessResult();
		/**结论复审**/
		$scope.opinionData=[];
		$scope.departOpinion=[];
		$scope.auditResult={};
		function selectAuditResultDate(){
			var param=['WARN_CHECK_AUDIT_RESULT','DEPARTMENT_OPINION']
			WarningAddService.getBaseFormParam(param).success(function(response){
				$scope.auditResult.auditOpinion='';
				$scope.auditResult.auditResult='';
			    if(response.WARN_CHECK_AUDIT_RESULT){
			    	$scope.opinionData=response.WARN_CHECK_AUDIT_RESULT;
			    }
			    if(response.DEPARTMENT_OPINION){
			    	$scope.departOpinion=response.DEPARTMENT_OPINION;
			    }
			    if($scope.auditResult.auditResult!=null){
			    	$scope.auditResult.result=$scope.auditResult.auditResult+'|'+$scope.auditResult.auditResultName;
				}
				if($scope.auditResult.auditOpinion!=null){
					$scope.auditResult.opinion=$scope.auditResult.auditOpinion+'|'+$scope.auditResult.auditOpinionName;;
				}
				getAuditResult();
			});
		}
		selectAuditResultDate();
		//复审
		function getAuditResult(){
			WarningAddService.getAuditResult({warnNo:warnNo})
			.success(function(res){
				if(res.auditResult){
					$scope.auditResult=res.auditResult;	
					if($scope.auditResult.auditResult){
						$scope.auditResult.result=$scope.auditResult.auditResult+'|'+$scope.auditResult.auditResultName;
					}
					if($scope.auditResult.auditOpinion){
						$scope.auditResult.opinion=$scope.auditResult.auditOpinion+'|'+$scope.auditResult.auditOpinionName;
					}
				}  
				if(!$scope.auditResult.sumAmount){
					$scope.auditResult.sumAmount=$scope.assessResult.sumAmount;
				}
				if(!$scope.resultNotice.amount&&$scope.auditResult.sumAmount){
					$scope.resultNotice.amount=$scope.auditResult.sumAmount;
				}
			});
		}
		$scope.changeNoticeAmount = function(){
			$scope.resultNotice.amount=$scope.auditResult.sumAmount;
		}
		$scope.changeAuditResult = function(){
			   if($scope.auditResult.result){
				   $scope.auditResult.auditResult=$scope.auditResult.result.split('|')[0];
				   $scope.auditResult.auditResultName=$scope.auditResult.result.split('|')[1];
			   }else{
				   $scope.auditResult.auditResult='';
				   $scope.auditResult.auditResultName='';
			   }
		   }
		   $scope.changeAuditOpinion = function(){
			   if($scope.auditResult.opinion){
				   $scope.auditResult.auditOpinion=$scope.auditResult.opinion.split('|')[0];
				   $scope.auditResult.auditOpinionName=$scope.auditResult.opinion.split('|')[1];
			   }else{
				   $scope.auditResult.auditOpinion='';
				   $scope.auditResult.auditOpinionName='';
			   }
		   }
		//暂存
    	$scope.saveWarning = function() { 
	           var params=getParams();
	           $scope.saveDialogload=true;
			   WarningAddService.saveHcpmsWarning(params).success(function(data){
				   $scope.saveDialogload=false;
				   Modal.alert(data.msg);
				   if(data.state==='0') {
					   WarningAddService.warningMarks = [];//初始化扣分参数
					   getAuditResult();
					   WarningScreenService.findPointCutTempScose(
			 				   WarningAddService.warningMarks,$stateParams.warnNo,'01',
			 				   $scope.warnMedicalData,$scope.warnStaffData,$scope.warnInsurData);
	               }
			   });
		   }
		   //验证信息
		   function isWarningNull(){			  
			   if(!$scope.auditResult.auditResult){
					Modal.alert("请选择自查报告审核结果!");
					return false;
				}
			   if($scope.auditResult.auditResult == '01'){
				   if($scope.prcoessTypeFlag&&!$scope.resultNotice){				   
					   Modal.alert("请填写结果告知书内容!");
					   return false;				  
				   }			  
				   if(!$scope.resultNotice.address||!$scope.resultNotice.phone
							||!$scope.resultNotice.startDate||!$scope.resultNotice.endDate||!$scope.resultNotice.problem
							||!$scope.resultNotice.decide||!$scope.resultNotice.amount||!$scope.resultNotice.noticeDate){
						 Modal.alert("结果告知书内容未填写完全,请完善!");
						 return false;					
					}				   
			   }			   
				if($scope.auditResult.auditResult != '01'&&!$scope.auditResult.auditOpinion){
					Modal.alert("自查不到位,科室处理意见不能为空!");
					return false;
				}
				if(!$scope.auditResult.sumAmount){
					Modal.alert("确认不合理费用不能为空!");
					return false;
				}
			   return true;
		   }
		   
		 //--------------------------------------------------------
			/**
			 * 显示附件
			 */
			$scope.path="";
			var params2 = {id:warnNo};
			CaseCommonService.showImage(params2).success(function(res){
				$scope.fileData = res.result.imgList;
			    $scope.path=res.path;
			});
		    
			//显示下载和查看按钮
			$scope.showId = "";
	        $scope.mouseover=function(id)
	        {
	        	 $scope.showId = id;
	        }
	        
	        /**
	         * 下载文件
	         */
	        $scope.downLoadFile=function(item){
	            var path="";
	            var suffix = item.name.substring(0,item.name.lastIndexOf('.'));
	            window.location = baseUrl + 'agreement/downloadFile.do?fileInfoId='+item.businessNo+'/insurance/'+suffix+
	                '&fileName='+item.name+'&path='+path;
	        }
	        /**
	         * 查看文件
	         */
	        /*$scope.openLoadFile=function(item){
	            var path= $scope.path+'/'+item.businessNo+'/insurance/'+ item.name;
	           var  param={filePath:path};
	            $http.post(baseUrl + 'agreement/exitFile.do',param).success(function(data) {
	                if(data.state!="error")
	                {
	                    window.open(baseUrl + '/file/openPdfFile.do?filePath='+path);
	                }else
	                {
	                    Modal.alert(data.msg);
	                }
	            })
	        }*/
		     //--------------------------------------------------------
		   //保存和暂存设置保存的内容
		   function getParams(){
		           var staffList=[],
				       insurList=[];
				   angular.forEach($scope.warnStaffData,function(data,index) {
					   var staff={};
					   if(data.code){
						   staff.code = data.code;
					   }
					   if(data.name){
						   staff.name = data.name;
					   }
					   staffList.push(staff);
				   });
				   angular.forEach($scope.warnInsurData,function(data,index) {
					   var insurance={};
					   if(data.code){
						   insurance.code = data.code;
					   }
					   if(data.name){
						   insurance.name = data.name;
					   }
					   insurList.push(insurance);
				   });
		           var params={
		        		      warnNo:warnNo,
		        		      status:$scope.warningFrom.status,
		        		      opinion:$scope.auditResult.auditResult,
		        		      beforePerson:$scope.assessResult.agent,
		        		      auditResult:$scope.auditResult,
		        		      staffList:staffList,
		        		      insurList:insurList,
		        		      resultNotice:$scope.resultNotice,
		        		      warnMarkTempDetails:WarningAddService.warningMarks
		                        }; 
		          return params;
		   }
		   //保存
		   $scope.submitWarning = function(){
			   if(!isWarningNull()){
				  return;
			   }		  
	           var params=getParams(); 
	           if($scope.auditResult.auditResult === '02'||$scope.auditResult.auditResult === '03')
	        	   params.isCheckBack="1";
	           else
	        	   params.isCheckBack="0";
	           $scope.saveDialogload=true;
	           WarningAddService.resultAuditProcess(params).success(function(data){
	        	   $scope.saveDialogload=false;
	        	   Modal.alert(data.msg);
				   if(data.state=='0') {
					   WarningAddService.warningMarks = [];//初始化扣分参数
					   if($stateParams.urlFlag){
					   		var urlFlag=$stateParams.urlFlag;
							FwaTabsetService.closeTab('warnQueryResultAudit','workingArea.warnAuditPost',{urlFlag:urlFlag});
					   	}else{
				   			FwaTabsetService.selectTab("warnQueryResultAudit.warningResultAuditList",null,false);
					   	}
	               }
			   });
		   }
	   $scope.backWarning = function(){
		   	WarningAddService.warningMarks = WarningAddService.warningMarkTemps;//初始化扣分参数
		   	if($stateParams.urlFlag){
		   		var urlFlag=$stateParams.urlFlag;
				FwaTabsetService.closeTab('warnQueryResultAudit','workingArea.warnAuditPost',{urlFlag:urlFlag});
		   	}else{
	   			FwaTabsetService.selectTab("warnQueryResultAudit.warningResultAuditList",null,false);
		   	}
        }
	 //扣分 mark：1.机构扣分，2.医务人员扣分，3参保人员扣分,data:数据集合
	   $scope.marking = function(mark,data,medicalCode,orgType){
		   var medicalCodeTemp=null;
			if(medicalCode&&!angular.isUndefined(medicalCode)){
				medicalCodeTemp = medicalCode;
			}
		   if(mark != 1 && medicalCodeTemp == null){
			   Modal.alert("请先增加医疗机构信息！");
				return null;
		   }else{
			   medicalCode = medicalCodeTemp;
		   }
		   markData(mark,data,medicalCode,orgType);//扣分数据参数加载
		   var modalInstance = $modal.open({
			      templateUrl: baseUrl+'views/hcpms/warning/warnEdit/warningDeductionDialog_view.html',
			      backdrop:'static',
				  size:'sm',
				  scope: $scope,
//				  scope:scope,
				  controller: 'WarningDeductionDialogCtrl'
			    });
			 //接收返回数据
			 modalInstance.result.then(function(item) {
				 if (!WarningAddService.warningMarks) {
					 WarningAddService.warningMarks = [];
					}
				 WarningAddService.warningMarks = item;
				 WarningScreenService.findPointCutTempScose(item,$stateParams.warnNo,'01',
						   $scope.warnMedicalData,$scope.warnStaffData,$scope.warnInsurData); 
	 	    });
	   }
	   //扣分数据参数加载
	   var markData = function(mark,data,medicalCode,orgType){
		   WarningAddService.mark = mark;
		   WarningAddService.warningMarkData = {
				   orgType:orgType,//0.机构，1.药店
				   medicalCode:medicalCode,//medicalCode:所属机构编号
				   code:data.code,//code:编号
				   name:data.name,//name:名称
				   caseType:'01',//案件类型caseType：01.预警,02.稽核
				   caseNo:$stateParams.warnNo,//案件编号
				   happenDate:$scope.warningFrom.warnDate,//案发日期
				   punishDateStart:$scope.warningFrom.startDate,// 惩罚起期
				   punishDateEnd:$scope.warningFrom.endDate,// 惩罚终期
				   warningMarks:WarningAddService.warningMarks//扣分项数据
				   };
	   }
	   $scope.saveDialogload=false;
	}]);
})();